package com.yunche.yunchebusiness.mvp.presenter

import com.alibaba.fastjson.JSONObject
import com.yunche.yunchebusiness.base.mvp.BasePresenter
import com.yunche.yunchebusiness.mvp.contract.UpdateContract
import com.yunche.yunchebusiness.mvp.model.UpdataModel
import com.yunche.yunchebusiness.network.exception.ErrorStatus
import com.yunche.yunchebusiness.network.exception.ExceptionHandle
import com.yunche.yunchebusiness.toRequestBody

/**
 * Create by Crcker on 2019/1/10 11:08
 * Email: Crcker@163.com
 */


class UpdatePresenter : BasePresenter<UpdateContract.View>(), UpdateContract.Presenter {
    private val model by lazy {
        UpdataModel()
    }

    override fun checkVersion(versionCode: String, type: Int) {
        checkViewAttached()
        var para = JSONObject()
        para["versionCode"] = versionCode
        para["terminalType"] = 4
        mRootView?.showLoading()
        var disposable = model.checkVersion(para.toJSONString().toRequestBody())
            .subscribe({
                mRootView!!.apply {
                    hideLoading()
                    if (it["resultCode"].asInt == ErrorStatus.SUCCESS) {
                        noNewVersion()
                    } else {
                        var isMust =
                            !(it["datas"].asJsonObject["updateType"] == null && it["datas"].asJsonObject["updateType"].asInt == 1)

                        hasNewVersion(
                            it["datas"].asJsonObject["downloadUrl"].asString,
                            it["datas"].asJsonObject["downloadUrl"].asString, isMust
                        )
                    }
                }
            }, {
                mRootView?.hideLoading()
                mRootView?.showError(ExceptionHandle.handleException(it))
            })

        addSubscription(disposable)
    }
}